<template>
  <div class="chart-container">
    <div v-if="loading" class="loading-overlay">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <div class="loading-text">{{ $t('loading') }}</div>
    </div>
    
    <div v-if="error" class="error-overlay">
      <el-icon class="error-icon"><Warning /></el-icon>
      <div class="error-text">{{ $t('dataLoadFailed') }}</div>
      <el-button size="small" @click="fetchData" class="retry-button">
        {{ $t('retryButton') }}
      </el-button>
    </div>
    
    <div ref="chart" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'
import anlyze from "../../apis/anlyze.js"

const { t, locale } = useI18n()
const chart = ref(null)
let myChart = null
const loading = ref(false)
const error = ref(false)

// 自定义颜色
const colors = [
  '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', 
  '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'
]

const initChart = () => {
  if (myChart) {
    myChart.dispose()
  }
  
  // 确保DOM已经渲染
  if (chart.value) {
    myChart = echarts.init(chart.value)
    
    // 设置响应式
    const resizeHandler = () => {
      myChart && myChart.resize()
    }
    
    window.addEventListener('resize', resizeHandler)
    
    // 组件卸载时移除事件监听
    onUnmounted(() => {
      window.removeEventListener('resize', resizeHandler)
    })
  }
}

// 获取后端数据并更新图表
const fetchData = async () => {
  loading.value = true
  error.value = false
  
  try {
    const res = await anlyze.activeMaps()
    
    // 活跃度类别映射表 (根据实际后端返回的category调整)
    const activityMap = {
      'highly_active': t('highlyActive'),
      'moderately_active': t('moderatelyActive'),
      'low_active': t('lowActive'),
      'inactive': t('inactive'),
      // 如果后端返回的是中文，也要处理
      '高度活跃': t('highlyActive'),
      '中度活跃': t('moderatelyActive'),
      '低度活跃': t('lowActive'),
      '不活跃': t('inactive')
    }
    
    // 格式化数据为 ECharts 需要的格式
    const chartData = res.map((item) => ({
      value: item.count,
      name: activityMap[item.category] || item.category,
    }))

    // 更新 ECharts 配置
    const option = {
      title: {
        text: t('activeDistribution'),
        left: 'center',
        top: 10,
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: '#e6e9ed',
        borderWidth: 1,
        textStyle: {
          color: '#5e6d82'
        }
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal',
        bottom: 10,
        left: 'center',
        itemWidth: 14,
        itemHeight: 14,
        textStyle: {
          color: '#5e6d82',
          fontSize: 12
        },
        formatter: function(name) {
          // 限制图例文字长度
          return name.length > 12 ? name.slice(0, 10) + '...' : name;
        }
      },
      series: [
        {
          name: t('activeCount'),
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '45%'], // 调整圆饼图位置，为底部图例留出空间
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          labelLine: {
            show: false,
          },
          data: chartData,
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx) {
            return Math.random() * 200;
          }
        },
      ],
      color: colors
    }
    
    // 通过 ref 更新 ECharts 图表
    if (!myChart) {
      initChart()
    }
    myChart.setOption(option)
    loading.value = false
  } catch (error) {
    console.error(t('dataLoadFailed'), error)
    loading.value = false
    error.value = true
  }
}

// 在组件挂载后获取数据并初始化图表
onMounted(() => {
  fetchData()
})

// 监听语言变化，重新加载图表
watch(locale, () => {
  fetchData()
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

.loading-overlay, .error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.loading-icon, .error-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.loading-icon {
  color: #409eff;
  animation: rotate 2s linear infinite;
}

.error-icon {
  color: #f56c6c;
}

.loading-text, .error-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 12px;
}

.retry-button {
  margin-top: 8px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
